/**
 * 路由扩展
 * */ import {
  NavigationFailure,
  RouteLocationRaw,
  useRouter,
  Router,
} from 'vue-router'

export interface PrefixRouter extends Router {
  getName(): string | undefined
  getQuery(): { [p: string]: string }
  getParams(): { [p: string]: string }
  // 当前路由是否有跳转前缀
  hasPrefix(): boolean
  // 使用前缀进行跳转
  prefixPush(
    to: RouteLocationRaw,
  ): Promise<NavigationFailure | void | undefined>
}

/**
 * 能更便捷使用prefix跳转的router hook
 * */
export function usePrefixRouter() {
  const router: PrefixRouter = {
    ...useRouter(),
    getName() {
      return router.currentRoute.value.name as string | undefined
    },
    getQuery() {
      return router.currentRoute.value.query as { [p: string]: string }
    },
    getParams() {
      return router.currentRoute.value.params as { [p: string]: string }
    },
    hasPrefix(): boolean {
      return !!router.currentRoute.value.meta?.prefix
    },
    prefixPush(to: any) {
      const prefix = <string | undefined>router.currentRoute.value.meta?.prefix
      if (!prefix) return router.push(to)
      if (typeof to === 'string') {
        let url = `/${prefix}`
        if (to.startsWith('/')) url += to
        else url += `/${to}`
        return router.push(url)
      }
      if (to.path) {
        if (to.path.startsWith('/')) to.path = `/${prefix}${to.path}`
        else to.path = `/${prefix}/${to.path}`
      }
      if (to.name) {
        to.name = `${prefix}-${to.name}`
      }
      return router.push(to)
    },
  }
  return router
}
